const CopyWebpackPlugin = require('copy-webpack-plugin')
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const TerserWebpackPlugin = require('terser-webpack-plugin');
const glob = require('glob');
const resolveDir = require('./paths');
const PurgeCSSPlugin = require('purgecss-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
const InlineChunkHtmlPlugin = require('inline-chunk-html-plugin')

module.exports = {
  mode: 'production',
  optimization: {
    usedExports: true,
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin(),
      new TerserWebpackPlugin({
        extractComments: false
      })
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [{
        from: 'public',
        globOptions: {
          ignore: ['**/index.html']
        }
      }]
    }),
    new MiniCssExtractPlugin({
      filename: 'css/name.[hash:8].css'
    }),
    new PurgeCSSPlugin({
      paths: glob.sync(`${resolveDir('./src')}/**/*`, {
        nodir: true
      }), // 读取本地文件
      safelist: function () {
        return {
          standard: ['html', 'ef'] // 不摇掉什么元素
        }
      }
    }),
    new BundleAnalyzerPlugin({
      analyzerMode: 'static'
    }),
    new CompressionPlugin({
      test: /\.(css|js)$/,
      minRatio: 0.8,
      threshold: 0,
      algorithm: 'gzip'
    }),
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime.*\.js/]) // 可以把js外链直接插入到html中
  ]
} 